<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <h2>注册</h2>
        </div>
      </template>

      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号（可选）" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="password_confirm">
          <el-input
            v-model="form.password_confirm"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleRegister" :loading="loading" style="width: 100%">
            注册
          </el-button>
        </el-form-item>

        <el-form-item>
          <div class="login-link">
            <span>已有账号？</span>
            <el-link type="primary" @click="$router.push('/login')">立即登录</el-link>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import logger from '../utils/logger'

export default {
  name: 'Register',
  setup() {
    const router = useRouter()
    const store = useStore()
    const formRef = ref(null)
    const loading = ref(false)

    const form = reactive({
      username: '',
      email: '',
      phone: '',
      password: '',
      password_confirm: ''
    })

    const validatePasswordConfirm = (rule, value, callback) => {
      if (value !== form.password) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { 
          validator: (rule, value, callback) => {
            if (!value || value.trim() === '') {
              callback() // 手机号可选，为空时通过验证
            } else if (!/^1[3-9]\d{9}$/.test(value)) {
              callback(new Error('请输入正确的手机号'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      password_confirm: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePasswordConfirm, trigger: 'blur' }
      ]
    }

    const handleRegister = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        loading.value = true

        // 构建注册数据
        const registerData = {
          username: form.username.trim(),
          email: form.email.trim(),
          password: form.password,
          password_confirm: form.password_confirm
        }
        
        // 如果手机号不为空，添加到数据中
        if (form.phone && form.phone.trim()) {
          registerData.phone = form.phone.trim()
        }

        const result = await store.dispatch('register', registerData)

        if (result.success) {
          // 注册成功后，提示用户登录
          ElMessage.success({
            message: result.message || '注册成功，请登录',
            duration: 3000,
            showClose: true
          })
          // 延迟跳转到登录页面，让用户看到成功提示
          setTimeout(() => {
            router.push({
              path: '/login',
              query: { 
                username: form.username.trim(),
                registered: 'true' 
              }
            })
          }, 1500)
        } else {
          // 处理错误信息
          let errorMsg = '注册失败，请检查输入信息'
          if (result.error) {
            errorMsg = result.error
          }
          // 如果有详细信息，也显示
          if (result.details) {
            logger.error('注册失败详情:', result.details)
          }
          ElMessage.error({
            message: errorMsg,
            duration: 5000,
            showClose: true
          })
          logger.error('注册失败:', result)
        }
      } catch (error) {
        logger.error('注册异常:', error)
        ElMessage.error('注册失败，请检查输入信息')
      } finally {
        loading.value = false
      }
    }

    return {
      formRef,
      form,
      rules,
      loading,
      handleRegister
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 60px);
  /* 南昌旅游特色：天空蓝到水蓝渐变 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 550px;
  border-radius: 20px;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.8) 100%);
  backdrop-filter: blur(10px);
  box-shadow: 0 10px 40px rgba(200, 16, 46, 0.2);
}

.card-header {
  text-align: center;
  padding: 10px 0;
}

.card-header h2 {
  margin: 0;
  /* 南昌红主题色 */
  color: #C8102E;
  font-size: 28px;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 8px 15px;
}

:deep(.el-button--primary) {
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  /* 南昌红到滕王阁金渐变 */
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  border: none;
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #D91E36 0%, #E6C866 100%);
  box-shadow: 0 6px 20px rgba(212, 175, 55, 0.4);
  transform: translateY(-2px);
}

.login-link {
  text-align: center;
  width: 100%;
  margin-top: 10px;
}

.login-link span {
  margin-right: 8px;
  color: #909399;
  font-size: 14px;
}

.login-link .el-link {
  font-size: 14px;
}
</style>

